<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-breadcrumb>
          <el-breadcrumb-item class="text">试题录入</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 表单 -->
      <el-form
        :model="questionsRulesForm"
        :rules="questionsRules"
        ref="questionsRulesFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="学科:" prop="subjectID">
          <el-select
            v-model="questionsRulesForm.subjectID"
            class="w375"
            placeholder="请选择"
            @change="catalog"
          >
            <el-option
              v-for="item in disciplinelist"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录:" prop="catalogID">
          <el-select
            v-model="questionsRulesForm.catalogID"
            class="w375"
            placeholder="请选择"
          >
            <el-option
              v-for="item in cataloglist"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业:" prop="enterpriseID">
          <el-select
            class="w375"
            v-model="questionsRulesForm.enterpriseID"
            placeholder="请选择"
          >
            <el-option
              v-for="item in enterpriselist"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市:" prop="city">
          <!-- <el-col :span="3"> -->
          <el-select
            v-model="questionsRulesForm.province"
            placeholder="请选择"
            style="width: 13%;"
            @change="district"
          >
            <el-option
              v-for="(ietm, index) in citylist"
              :key="index"
              :label="ietm"
              :value="ietm"
            ></el-option>
          </el-select>
          <!-- </el-col> -->
          <!-- <el-col :span="4"> -->
          <el-select
            v-model="questionsRulesForm.city"
            placeholder="请选择"
            style="width: 13%;"
          >
            <el-option
              v-for="(item, index) in districtlist"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          <!-- </el-col> -->
        </el-form-item>
        <el-form-item label="方向:" prop="direction">
          <el-select
            class="w375"
            v-model="questionsRulesForm.direction"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in directionlist"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型:" prop="question">
          <el-radio-group v-model="questionsRulesForm.questionType">
            <el-radio
              v-for="item in questionlist"
              :key="item.value"
              :label="item.value + ''"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度:" prop="difficulty">
          <el-radio-group v-model="questionsRulesForm.difficulty">
            <el-radio
              v-for="item in difficultylist"
              :key="item.value"
              :label="item.value + ''"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <!-- 富文本题干 -->
        <el-form-item label="题干:" prop="question" style="height:300px;">
          <template>
            <div>
              <quill-editor
                ref="myTextEditor"
                v-model="questionsRulesForm.question"
                :options="editorOption"
                style=" height:250px; width: 1104;"
              ></quill-editor>
            </div>
          </template>
        </el-form-item>
        <!-- 选项 -->
        <el-form-item
          label="选项:"
          v-show="questionsRulesForm.questionType !== '3'"
        >
          <div v-for="(item, index) in questionsRulesForm.options" :key="index">
            <el-radio-group
              v-if="questionsRulesForm.questionType == '1'"
              v-model="item.isRight"
              @change="handel(item)"
            >
              <el-radio :label="1">
                <span>{{ item.code }}</span>
              </el-radio>
            </el-radio-group>
            <el-checkbox
              v-else-if="questionsRulesForm.questionType == '2'"
              v-model="item.isRight"
              :checked="item.isRight == 1"
            >
              <span>{{ item.code }}</span>
            </el-checkbox>
            <el-input
              class="input_adc"
              v-model="item.title"
              placeholder=""
            ></el-input>
            <div class="index" @click="getindex(index)">
              <el-upload
                action="http://localhost:3000/upload/"
                class="abc"
                v-model="item.img"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img class="avatar" v-if="item.img" :src="item.img" />
                <span class="text" align="center">上传图片</span>
              </el-upload>
              <i class="el-icon-circle-close" @click="romover"></i>
            </div>
          </div>
          <!-- <div>
              <el-radio :label="2">
                <span>B:</span>
                <el-input
                  class="input_adc"
                  v-model="questionsRulesForm.input"
                  placeholder=""
                ></el-input>
                <el-upload action="" class="abc">
                  <img
                    v-if="questionsRulesForm.imageUrl"
                    :src="questionsRulesForm.imageUrl"
                  />
                  <i v-else class="el-icon-circle-close"></i>
                  <span class="text" align="center">上传图片</span>
                </el-upload>
              </el-radio>
            </div>
            <div>
              <el-radio :label="3">
                <span>C:</span>
                <el-input
                  class="input_adc"
                  v-model="questionsRulesForm.input"
                  placeholder=""
                ></el-input>
                <el-upload action="" class="abc">
                  <img
                    v-if="questionsRulesForm.imageUrl"
                    :src="questionsRulesForm.imageUrl"
                  />
                  <i v-else class="el-icon-circle-close"></i>
                  <span class="text" align="center">上传图片</span>
                </el-upload>
              </el-radio>
            </div>
            <div>
              <el-radio :label="6">
                <span>D:</span>
                <el-input
                  class="input_adc"
                  v-model="questionsRulesForm.input"
                  placeholder=""
                ></el-input>
                <el-upload action="" class="abc">
                  <img
                    v-if="questionsRulesForm.imageUrl"
                    :src="questionsRulesForm.imageUrl"
                  />
                  <i v-else class="el-icon-circle-close"></i>
                  <span class="text" align="center">上传图片</span>
                </el-upload>
              </el-radio>
            </div> -->
          <el-button
            class="disabled"
            type="danger"
            :disabled="
              this.questionsRulesForm.questionType == '2' ? false : true
            "
            @click="addAOption"
            >+增加选项与答案</el-button
          >
        </el-form-item>
        <!-- 解析视频 -->
        <el-form-item label="解析视频:" prop="videoURL">
          <el-input
            v-model="questionsRulesForm.videoURL"
            placeholder=""
            style="width:375px"
          ></el-input>
        </el-form-item>
        <!-- 答案解析富文本 -->
        <el-form-item
          label="答案解析:"
          prop="disciplinefwb"
          style="height:300px;"
        >
          <template>
            <div>
              <quill-editor
                ref="myTextEditor"
                v-model="questionsRulesForm.answer"
                :options="editorOption"
                style=" height:250px; width: 1104;"
              ></quill-editor>
            </div>
          </template>
        </el-form-item>
        <!-- 题目备注 -->
        <el-form-item label="题目备注:">
          <el-input
            type="textarea"
            :rows="4"
            placeholder=""
            v-model="questionsRulesForm.remarks"
            style="width:375px"
          >
          </el-input>
        </el-form-item>
        <!-- 试题标签 -->
        <el-form-item label="试题标签:">
          <template>
            <el-select
              v-model="questionsRulesForm.tags"
              class="w375"
              multiple
              placeholder="请选择试题标签"
            >
              <el-option
                v-for="item in PaperLabellist"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              >
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <!-- 确认提交 -->
        <el-form-item>
          <el-button
            type="primary"
            :class="this.$route.query.id ? 'ls' : ''"
            @click="submitForm('questionsRulesFormRef')"
            >{{ this.$route.query.id ? '确认修改' : '确认提交' }}</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { simple as disciplinelist } from '@/api/hmmm/subjects'
import {
  simple as cataloglist,
  detail as detailid
} from '@/api/hmmm/directorys'
import { list as enterpriselist } from '@/api/hmmm/companys'
import { add, detail as details, update } from '@/api/hmmm/questions'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import { simple as PaperLabel } from '@/api/hmmm/tags'

export default {
  name: 'QuestionsNew',
  data() {
    return {
      questionsRulesForm: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 市
        city: '', // 区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干富文本内容
        options: [
          { code: 'A', title: null, img: null, isRight: 0 },
          { code: 'B', title: null, img: null, isRight: 0 },
          { code: 'C', title: null, img: null, isRight: 0 },
          { code: 'D', title: null, img: null, isRight: 0 }
        ],
        imageUrl: '',
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备足
        tags: '' // 试题标签
      },
      disciplinelist: [], // 接口调用接受的学科
      cataloglist: [], // 接口调用接受的目录
      enterpriselist: [], // 接口调用接受的企业
      citylist: [], // 接口调用固定的市区
      districtlist: [], // 通过选中市区以后过滤出来的区
      directionlist: [], // 接口调用固定的方向
      questionlist: [], // 接口调用固定的题型
      difficultylist: [], // 接口调用固定的难度
      PaperLabellist: [], // 接口调用的试题标签
      clearable: false,
      optionid: 4, // 选项id
      optionindex: 0, // 选项adc 索引
      currentUploadImg: null, // 上传那图片的索引
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'], // 引用，代码块
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['image', 'link'] // 上传图片
          ]
        }
      },
      questionsRules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ],
        city: [{ required: true, message: '请选地区', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        question: [{ required: true, message: '请选择题型', trigger: 'blur' }],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        videoURL: [
          { required: true, message: '请输入视频地址', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 学科列表
    this.discipline(),
      // 企业列表
      this.enterprise(),
      // 城市列表
      this.city(),
      // 方向
      this.direction(),
      // 题型和难度
      this.question(),
      // 基础题库点击修改跳转进来
      this.details()
  },
  watch: {
    $route: function() {
      this.details()
    }
  },
  methods: {
    onEditorChange({ editor, html, text }) {
      this.content = html
    },
    // 学课列表
    async discipline() {
      try {
        const { data } = await disciplinelist()
        // console.log(data, 1)
        this.disciplinelist = data
      } catch (err) {
        console.log(err)
      }
    },
    // 目录列表
    async catalog() {
      if (!this.$route.query.id) {
        this.questionsRulesForm.catalogID = ''
        this.questionsRulesForm.tags = ''
      }
      try {
        const { data } = await cataloglist({
          subjectID: this.questionsRulesForm.subjectID
        })
        console.log(data, 2)
        this.cataloglist = data
      } catch (err) {
        console.log(err)
      }
      try {
        const { data } = await PaperLabel({
          subjectID: this.questionsRulesForm.subjectID
        })
        // console.log(data, 'lwj')
        this.PaperLabellist = data
      } catch (err) {
        console.log(err)
      }
    },
    // 企业列表
    async enterprise() {
      try {
        const { data } = await enterpriselist()
        // console.log(data, 123)
        this.enterpriselist = data.items
      } catch (err) {
        console.log(err)
      }
    },
    // 城市列表
    city() {
      const b = provinces()
      // console.log(b)
      this.citylist = b
    },
    // 市区列表
    district() {
      if (!this.$route.query.id) {
        this.questionsRulesForm.city = ''
      }
      const b = citys(this.questionsRulesForm.province)
      // console.log(b, 132)
      this.districtlist = b
    },
    // 方向列表
    direction() {
      const b = direction
      // console.log(b)
      this.directionlist = b
    },
    // 题型列表和难度列表
    question() {
      this.questionlist = questionType
      this.difficultylist = difficulty
      // console.log(this.questionlist, this.difficultylist)
    },
    //  添加选项与答案
    addAOption() {
      if (this.optionid == 12) return false
      this.optionid++
      this.optionindex++
      const span = ['D:', 'E:', 'F:', 'G:', 'H:', 'I:', 'J:', 'K:', 'L:']
      const list = {
        code: span[this.optionindex],
        title: null,
        img: null,
        isRight: 0
      }
      this.questionsRulesForm.options.push(list)
      console.log(list)
    },
    getindex(index) {
      this.currentUploadImg = index
    },
    // 图片文件列表上传时的函数
    handleAvatarSuccess(res, file) {
      this.questionsRulesForm.options[
        this.currentUploadImg
      ].img = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //  删除图片
    romover() {
      // console.log(this.currentUploadImg, 1789)
      this.questionsRulesForm.options[this.currentUploadImg].img = null
    },
    // 提交
    submitForm() {
      this.$refs.questionsRulesFormRef.validate(async valid => {
        // console.log(valid)
        if (valid) {
          // 通过id判断是上传还是修改
          if (this.$route.query.id) {
            // 修改基础题库
            this.questionsRulesForm.tags = this.questionsRulesForm.tags.join(
              ','
            )
            try {
              // console.log(this.questionsRulesForm, 123)
              const { data } = await update(this.questionsRulesForm)
              // console.log(data)
              this.$router.push('list')
            } catch (err) {
              console.log(err)
            }
          } else {
            // 添加基础题库
            this.questionsRulesForm.tags = this.questionsRulesForm.tags.join(
              ','
            )
            console.log(this.questionsRulesForm, 951)
            try {
              await add(this.questionsRulesForm)
              // console.log(data)
              this.$router.push('list')
            } catch (err) {
              console.log(err)
            }
          }
        } else {
          console.log('error submit!!')
          // const options = {
          //   code: this.optionlist[this.questionsRulesForm.option],
          //   title: this.questionsRulesForm.input,
          //   img: this.questionsRulesForm.imageUrl
          // }
          console.log(this.questionsRulesForm)
          return false
        }
      })
    },
    handel(currentItem) {
      console.log(currentItem)
      this.questionsRulesForm.options.forEach(item1 => {
        if (item1 !== currentItem) {
          item1.isRight = 0
        }
      })
    },
    // 基础题库修改
    async details() {
      if (this.$route.query.id) {
        // 获取数据但是目录给我的是数字不是字符串
        try {
          const { data } = await details({
            id: this.$route.query.id
          })
          // console.log(data, 7896666)
          this.questionsRulesForm = data
        } catch (err) {
          console.log(err)
        }
        // 通过catalogID的id再去寻找目录的名称
        // try {
        //   const { data } = await detailid({
        //     id: this.questionsRulesForm.catalogID
        //   })
        //   // console.log(data, 123456)
        //   this.questionsRulesForm.catalogID = data.directoryName
        // } catch (err) {
        //   console.log(err)
        // }
        // 通过返回的tags的id再去寻找我的试题标签名称
        // try {
        //   const { data } = await detailtags({
        //     id: this.questionsRulesForm.tags
        //   })
        //   console.log(data, 753)
        //   this.questionsRulesForm.tags = data.tagName
        // } catch (err) {
        //   console.log(err)
        // }
        this.questionsRulesForm.tags = this.questionsRulesForm.tags.split(',')
        this.catalog()
        this.district()
        // console.log(this.questionsRulesForm.tags,233);
        // console.log(this.PaperLabellist,233);
      } else {
        return (this.questionsRulesForm = {
          subjectID: '', // 学科
          catalogID: '', // 目录
          enterpriseID: '', // 企业
          province: '', // 市
          city: '', // 区
          direction: '', // 方向
          questionType: '1', // 题型
          difficulty: '1', // 难度
          question: '', // 题干富文本内容
          options: [
            { code: 'A', title: null, img: null, isRight: 0 },
            { code: 'B', title: null, img: null, isRight: 0 },
            { code: 'C', title: null, img: null, isRight: 0 },
            { code: 'D', title: null, img: null, isRight: 0 }
          ],
          imageUrl: '',
          videoURL: '', // 解析视频
          answer: '', // 答案解析
          remarks: '', // 题目备足
          tags: '' // 试题标签
        })
      }
    }
  }
}
</script>

<style scoped>
::v-deep .el-upload {
  display: block;
}

::v-deep.container {
  padding: 20px;
}
.clearfix .text {
  font-size: 16px;
  color: #303133;
}
::v-deep .w375 {
  width: 375px;
}
::v-deep .el-select > .el-input {
  padding-left: 5px !important ;
}
::v-deep.danxuan {
  padding-right: 16px !important;
}
::v-deep .option {
  margin-top: 10px;
}
.abc {
  display: inline-block;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
  margin-left: 5px;
}
.avatar {
  width: 98px;
  height: 60px;
  position: absolute;
  left: 0px;
  top: 0;
}
.input_adc {
  background-color: #fff;
  background-image: none;
  border-radius: 4px;
  box-sizing: border-box;
  color: #606266;
  display: inline-block;
  font-size: inherit;
  outline: 0;
  /* // transition: border-color .2s cubic-bezier(.645,.045,.355,1); */
  width: 240px;
  height: 36px;
  line-height: 36px;
  text-align: center;
  margin-left: 10px;
}
.el-icon-circle-close {
  position: absolute;
  left: 399px;
  font-size: 18px;
  z-index: 999;
}

el-radio-group .disabled {
  width: 123px;
  height: 32px;
  color: #fff;
  padding: 20px;
}
.el-button--danger {
  margin-top: 20px;
}
.el-radio {
  margin: 10px 0;
}
::v-deep .el-radio__label {
  padding-right: 27px;
}
.index {
  display: inline-block;
  margin-top: 10px;
}
.ls {
  color: #fff;
  background-color: #67c23a;
  border-color: #67c23a;
}
</style>
